import { defineStore } from "pinia";

// import { loginApi, logoutApi } from "@/api/auth";
import { getCurrentUserInfo } from "@/api/v-sys-service/sys-manage/user/index.js";
import { resetRouter } from "@/router";
import { store } from "@/store";

import {useSessionStorage} from "@vueuse/core";
import * as api from "@/api/v-sys-service/sys-manage/auth/index.js";

export const useUserStore = defineStore("user", () => {
  const user = {
    roles: [],
    perms: [],
  };

  const token = useSessionStorage("accessToken", "");
  const setToken = (value) => {
    token.value = value
  }

  /**
   * 登录
   *
   */
  const login = (loginData) => {
    return new Promise((resolve, reject) => {
      api.login(loginData)
        .then((response) => {
          const { code } = response
          const { tokenType, accessToken } = response.data
          if (code === 200) {
            token.value = tokenType + " " + accessToken// Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            resolve()
          } else {
            reject()
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      getCurrentUserInfo()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          if (!data.roles || data.roles.length <= 0) {
            reject("getCurrentUserInfo: roles must be a non-null array!");
            return;
          }
          Object.assign(user, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 注销
  const logout = () => {
    return new Promise((resolve, reject) => {
      api.logout()
        .then(() => {
          resetStore();
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /** 清空缓存 */
  const resetStore = () => {
    resetRouter();
    token.value = "";
    Object.assign(user, { roles: [], perms: [] });
  }
  return {
    token,
    setToken,
    user,
    login,
    getInfo,
    logout,
    resetStore,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
